<template>
  <div class="counter-container">
    <!-- 数量 -1 按钮 -->
    <button type="button" class="btn btn-light btm-sm" @click="onSubClick">
      -
    </button>
    <!-- 输入框 -->
    <input
      type="number"
      class="form-control form-control-sm ipt-num"
      v-model.number.lazy="number"
    />
    <!-- 数量 +1 按钮 -->
    <button type="button" class="btn btn-light btm-sm" @click="onAddClick">
      +
    </button>
  </div>
</template>

<script>
export default {
  name: 'EsCounter',
  emits:['numChange'],
  props: {
    // 初始数量值【只读数据】
    num: {
      type: Number,
      default: 0
    },
    // 最小值
    min: {
      type: Number,
      default: NaN
    }
  },
  data() {
    return {
      number: this.num
    }
  },
  watch: {
    number(newVal) {
      const parseResult = parseInt(newVal)
      if (isNaN(parseResult) || parseResult < 1) {
        this.number = 1
        return
      }

      // 判断输入的是否是小数
      if (String(newVal).indexOf('.') !== -1) {
        // 转换为整数的结果parseResult赋值给number
        this.number = parseResult
        return
      }

      // 触发自定义事件,把最新的 number 数值传递给组件的使用者
      this.$emit('numChange', this.number)

    //   console.log(this.number)
    }
  },
  methods: {
    onSubClick() {
      if (!isNaN(this.min) && this.number - 1 < this.min) return

      this.number--
    },
    onAddClick() {
      this.number++
    }
  }
}
</script>

<style lang="less" scoped >
.counter-container {
  display: flex;
  // 按钮的样式
  .btn {
    width: 25px;
  }
  // 输入框的样式
  .ipt-num {
    width: 34px;
    text-align: center;
    margin: 3px 4px 0px;
  }
}
</style>